package com.ww.springboot.boot.algorithm.tree;

import com.itextpdf.styledxmlparser.jsoup.select.Collector;
import org.apache.poi.ss.formula.functions.T;

import java.util.*;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

/**
 * 描述：二叉树实现
 * <p>
 * <p>
 * 用队列创建树
 * 用队列记录需要填充的节点 先进先出
 *
 * @author 🧑 ‍wanwei
 * @since 2022-01-06 17:29
 */
public class TwoTreeDemo4<T> {
    private static int i;
    private static TreeNode treeNodeOne;
    private static Queue<TreeNode> queue;

    public TwoTreeDemo4() {
        i = 0;
        treeNodeOne = new TreeNode();
        queue = new LinkedList<>();
    }

    public static void main(String[] args) {
        List<String> list = IntStream.range(1, 9).boxed().map(i -> String.valueOf(i)).collect(Collectors.toList());
        TwoTreeDemo4<String> twoTreeDemo4 = new TwoTreeDemo4();
        twoTreeDemo4.buildTree(list);
        System.out.println(treeNodeOne);
        //左序遍历
        getLeftValue(treeNodeOne);
    }

    /**
     * 左序遍历
     *
     * @param treeNode
     */
    private static void getLeftValue(TreeNode treeNode) {
        if (treeNode == null) {
            return;
        }
        System.out.println(treeNode.getVal());
        getLeftValue(treeNode.getLeft());
        getLeftValue(treeNode.getRight());
    }

    /**
     * 从上往下 从左往右构建tree
     * @param arrays
     * @return
     */
    public TreeNode buildTree(List<T> arrays) {
        //
        queue.offer(treeNodeOne);
        while (i < arrays.size()) {
            setValues(queue.poll(), arrays);
            i++;
        }
        while (!queue.isEmpty()) {
            TreeNode treeNode = queue.poll();
            treeNode.setVal(0);
        }
        return treeNodeOne;
    }

    private void setValues(TreeNode treeNode, List<T> list) {
        treeNode.setVal(list.get(i));
        TreeNode treeNodeLeft = new TreeNode();
        TreeNode treeNodeRight = new TreeNode();
        treeNode.setLeft(treeNodeLeft);
        treeNode.setRight(treeNodeRight);
        queue.offer(treeNodeLeft);
        queue.offer(treeNodeRight);
    }


}
